<template>
  <div class="art-container">
    <div class="art-top">
      <div class="art-search">
        <el-input
          placeholder="请输入你要搜索的艺术品"
          v-model="queryParams.key"
          @keyup.native.enter="search"
          size="small"
          @clear="search"
          clearable
        ></el-input>
        <el-select
          v-model="queryParams.video_type"
          clearable
          @change="typeChange"
          class="search-select"
          placeholder="请选择"
          size="small"
        >
          <el-option v-for="item in typeList" :key="item.data_id" :label="item.name" :value="item.data_id"></el-option>
        </el-select>
      </div>
      <div class="art-btn"><el-button type="primary" size="small" @click="isShowDialog = true">新增</el-button></div>
    </div>

    <el-scrollbar style="height: calc(100vh - 190px)" class="scrollbar" id="scroll-bar">
      <el-table :data="list">
        <el-table-column label="id" prop="data_id"></el-table-column>
        <el-table-column label="封面图">
          <template slot-scope="scope">
            <el-image
              v-if="scope.row.video_page"
              style="width: 100px; height: 40px"
              :src="scope.row.video_page"
              :preview-src-list="[scope.row.video_page]"
              fit="cover"
            ></el-image>
            <span v-else>暂无图片</span>
          </template>
        </el-table-column>
        <el-table-column label="视频名称" prop="video_name">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="scope.row.video_name" placement="top-start">
              <div>
                {{ scope.row.video_name }}
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="视频简介" prop="video_comment">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="scope.row.video_comment" placement="top-start">
              <div>
                {{ scope.row.video_comment }}
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="所属艺术家" prop="art_name"></el-table-column>
        <el-table-column label="最后修改时间" width="160" prop="data_update_time"></el-table-column>
        <el-table-column label="是否推荐" prop="association_job">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.recommend"
              @change="onRecommend(scope.row)"
              :active-value="1"
              :inactive-value="0"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="视频地址" prop="video_path">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="scope.row.video_path" placement="top-start">
              <div>
                {{ scope.row.video_path }}
              </div>
            </el-tooltip>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="440">
          <template slot-scope="scope">
            <el-upload
              action=""
              class="avatar-uploader"
              style="width: 90px; float: left"
              :show-file-list="false"
              :on-progress="uploadVideoProcess"
              :on-success="handleVideoSuccess"
              :on-error="handleVideoError"
              :http-request="httpRequest"
              :on-change="
                (file) => {
                  videoChange(file, scope.row);
                }
              "
            >
              <el-button size="mini">上传视频</el-button>
              <el-progress
                v-if="videoFlag && uploadVideoId == scope.row.data_id"
                :percentage="videoUploadPercent"
                style="margin-top: 30px"
              ></el-progress>
            </el-upload>
            <el-upload
              action="/ws"
              class="avatar-uploader"
              style="width: 90px; float: left"
              :show-file-list="false"
              :before-upload="
                (file) => {
                  beforeAvatarUpload(file, scope.row.data_id);
                }
              "
            >
              <el-button size="mini">上传封面</el-button>
            </el-upload>
            <el-button type="primary" @click="updVideoType(scope.row.data_id, scope.row)" size="mini">修改</el-button>
            <el-button type="danger" @click="delVideoType(scope.row.data_id)" size="mini">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-scrollbar>

    <paging ref="page" :func="getList"></paging>

    <el-dialog @closed="onClose" :title="modelTitle" :visible.sync="isShowDialog">
      <el-form :model="dataParams" :rules="rules" ref="dataParams" label-width="80px" class="demo-dataParams">
        <el-form-item label="视频名称" prop="video_name">
          <el-input v-model="dataParams.video_name"></el-input>
        </el-form-item>

        <el-form-item label="视频简介" prop="video_comment">
          <el-input v-model="dataParams.video_comment" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="是否推荐" prop="recommend">
          <el-switch v-model="dataParams.recommend" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>
        <el-form-item label="艺术家" prop="art_id">
          <el-select
            v-model="dataParams.art_id"
            remote
            filterable
            :remote-method="remoteMethod"
            :loading="queryLoading"
          >
            <el-option
              v-for="item in userList"
              :key="item.data_id"
              :label="item.name"
              :value="item.data_id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="视频类型" prop="video_type">
          <el-select v-model="dataParams.video_type">
            <el-option
              v-for="item in typeList"
              :key="item.data_id"
              :label="item.name"
              :value="item.data_id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShowDialog = false">取 消</el-button>
        <el-button type="primary" @click="dialogConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import paging from '@/components/paging';
  import { other } from '@/api/prefix';
  import artisManage from '@/api/artis';
  import videoManage from '@/api/video';
  import axios from 'axios';
  import videoTypeManage from '@/api/videoType';
  import { qiniuUploadFile } from '@/utils/QiniuUpload';
  export default {
    name: 'video-view',
    components: {
      paging,
    },
    data() {
      return {
        dataList: [],
        queryParams: {
          key: '',
          video_type: '',
        },
        option: {
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)',
        },
        modelTitle: '新增视频',
        videoFlag: true,
        uploadVideoId: '',
        videoUploadPercent: 0,
        options: [
          {
            value: 'all',
            label: '所有视频',
          },
          {
            value: 'recommend',
            label: '推荐视频',
          },
        ],
        optionValue: 'all',
        userList: [],
        typeList: [],
        list: [],
        value1: '',
        value2: '',

        dataParams: {
          video_name: '', //姓名
          video_type: '', //类型
          video_comment: '',
          art_id: '',
          recommend: '',
        },
        isShowDialog: false,
        updId: '',
        rules: {
          video_name: [{ required: true, message: '请输入视频名', trigger: 'blur' }],
          video_type: [{ required: true, message: '请选择艺术类型', trigger: 'change' }],
        },
        queryLoading: false,
      };
    },
    async mounted() {
      let typeRes = await videoTypeManage.getVideoType({ notPagination: true });
      this.typeList = typeRes.item_list;
      let userRes = await artisManage.getArtis({ notPagination: true });
      this.userList = userRes.item_list;
      this.refresh();
    },
    methods: {
      async remoteMethod(query) {
        // if (!query) return;
        this.loading = true;
        let userRes = await artisManage.getArtis({ key: query, notPagination: true });
        this.userList = userRes.item_list;
        this.loading = false;
      },
      refresh() {
        this.$refs.page.refresh();
      },
      search() {
        this.$refs.page.search();
      },
      typeChange() {
        this.$refs.page.refresh();
      },
      getList(callback) {
        console.log(this.queryParams);
        if (this.optionValue === 'recommend') {
          videoManage.getRecommentVideoType(this.queryParams).then((res) => {
            let total = res.total_count;
            this.list = res.item_list;
            callback(this.list, total);
          });
        } else {
          videoManage.getVideoType(this.queryParams).then((res) => {
            let total = res.total_count;
            this.list = res.item_list;
            callback(this.list, total);
          });
        }
      },
      async beforeAvatarUpload(file, id) {
        let res = await qiniuUploadFile(file, 'video');
        if (res) {
          await videoManage.updVideoType(id, { video_page: res.key });
          this.$message({
            message: '封面上传成功',
            type: 'success',
          });
          this.refresh();
        }

        // console.log(id);
        // const formData = new FormData();
        // formData.append('上传的key值', file);
        // await videoManage.setVideoTypeImage(id, formData);
        // this.refresh();
      },
      handleVideoSuccess(res, file) {
        //视频上传成功之后返回视频地址
        this.videoFlag = false;
        this.videoUploadPercent = 0;
      },
      handleVideoError(err) {
        console.log('err', err);
        // this.$message.error(err)
        this.videoUploadPercent = 0;
        this.videoFlag = false;
      },
      uploadVideoProcess(event, file, fileList) {
        // this.videoFlag = true;
        // this.videoUploadPercent = parseInt(file.percentage);
        // console.log('this.videoUploadPercent', file.percentage);
      },
      httpRequest() {},
      async videoChange(file, row) {
        console.log('file', file.raw, row);
        this.uploadVideoId = row.data_id;
        var that = this;
        const api = process.env.NODE_ENV === 'development' ? '/webapi' : '/';
        let formData = new FormData();
        formData.append('上传的key值', file.raw);
        this.$loading(this.option);

        let res = await qiniuUploadFile(file, 'video', (progressEvent) => {
          //原生获取上传进度的事件
          if (progressEvent.lengthComputable) {
            console.log(progressEvent);
            that.videoFlag = true; // 显示进度条
            that.videoUploadPercent = parseInt((progressEvent.loaded / progressEvent.total) * 100); // 动态获取文件上传进度
            if (that.videoUploadPercent >= 99) {
              that.videoUploadPercent = 99; // 一秒后关闭进度条
            }
          }
        });
        if (res) {
          await videoManage.updVideoType(this.uploadVideoId, { video_path: res.key });
          this.$message({
            message: '视频上传成功',
            type: 'success',
          });
          that.videoUploadPercent = 100;
          setTimeout(() => {
            that.videoFlag = false;
            that.videoUploadPercent = 0;
          }, 1000);
          this.refresh();
        } else {
          this.$message.error('上传失败，请联系管理员');
        }
        this.$loading().close();

        // axios({
        //   method: 'post',
        //   url:
        //     api +
        //     other +
        //     '/famous_video/' +
        //     this.uploadVideoId +
        //     '?op=upload_file&name=video_path&ak=' +
        //     localStorage.ak,
        //   data: formData,
        //   headers: {
        //     'Content-Type': 'multipart/form-data',
        //   },
        //   onUploadProgress: function (progressEvent) {
        //     //原生获取上传进度的事件
        //     if (progressEvent.lengthComputable) {
        //       console.log(progressEvent);
        //       that.videoFlag = true; // 显示进度条
        //       that.videoUploadPercent = parseInt((progressEvent.loaded / progressEvent.total) * 100); // 动态获取文件上传进度
        //       if (that.videoUploadPercent >= 99) {
        //         that.videoUploadPercent = 99; // 一秒后关闭进度条
        //       }
        //     }
        //   },
        // })
        //   .then((res) => {
        //     console.log(res.data.status);
        //     if (res.data.status == '$SUCCESS') {
        //       that.$message({
        //         message: '视频上传成功',
        //         type: 'success',
        //       });
        //       that.videoUploadPercent = 100;
        //       setTimeout(() => {
        //         that.videoFlag = false;
        //         that.videoUploadPercent = 0;
        //       }, 1000);
        //       // that.dialogVisible = false
        //       // that.$emit('getdata', 0)
        //     } else {
        //       that.$message.error('上传失败，请联系管理员');
        //     }
        //   })
        //   .finally(() => {
        //     this.refresh();
        //     this.$loading().close();
        //   });
        // const formData = new FormData();
        // formData.append('上传的key值', file.raw);
        // this.uploadVideoId = row.data_id
        // // this.videoUploadPercent = 0
        // // const timer = setInterval(() => {
        // //   if (this.videoUploadPercent >= 99) {
        // //     this.videoUploadPercent = 100
        // //     this.videoFlag = false
        // //     clearInterval(timer)
        // //     return
        // //   }
        // //   this.videoUploadPercent += 1
        // // }, 20)
        // const res = await videoManage.uploadVideo(row.data_id, formData);
        // console.log('上传结果', res )
        // if (res) {
        //   this.videoUploadPercent = 100
        //   this.videoFlag = false
        //   clearInterval(timer)
        // }
        // if (file.status === 'success') {
        //   this.videoUploadPercent = 100
        //   this.videoFlag = false
        // }
        // let opus_id = await videoManage.imageMap({
        //   image_list: [
        //     {
        //       image_src_url: url,
        //       image_src_type: 'local',
        //       image_name: url.split('/')[2],
        //       type: 1,
        //       access_type: 0,
        //       note: '',
        //     },
        //   ],
        // });
        // await videoManage.updVideoType(row.data_id, { ...row, opus_id });
      },
      async onRecommend(row) {
        await videoManage.updVideoType(row.data_id, row);
        this.refresh();
      },
      updVideoType(data_id, row) {
        this.dataParams = row;
        this.updId = data_id;
        this.isShowDialog = true;
      },
      async delVideoType(data_id) {
        this.$alert('是否确定删除该视频', '删除', {
          confirmButtonText: '确定',
          callback: async (action) => {
            if (action === 'confirm') {
              await videoManage.delVideoType(data_id);
              this.refresh();
            }
          },
        });
      },
      async dialogConfirm() {
        this.$refs.dataParams.validate(async (valid) => {
          if (valid) {
            let res = null;
            if (this.updId) {
              this.modelTitle = '编辑视频';
              res = await videoManage.updVideoType(this.updId, {
                ...this.dataParams,
              });
            } else {
              this.modelTitle = '新增视频';
              res = await videoManage.setVideoType({
                ...this.dataParams,
              });
            }
            if (res) {
              this.isShowDialog = false;
              this.updId = '';
              this.refresh();
            }
          }
        });
      },
      onClose() {
        this.updId = '';
        this.dataParams = {
          video_name: '',
          comment: '',
          art_id: '',
          video_comment: '',
          video_type: '', //类型
        };
      },
    },
  };
</script>

<style lang="less" scoped>
  .art-container {
    height: 100%;
    .art-top {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .art-search {
        display: flex;
        .search-select {
          margin-left: 12px;
        }
        .search-data {
          display: flex;
          div {
            margin-left: 12px;
          }
        }
      }
    }
  }
</style>
